<?php

namespace app\api\controller;
use think\Db;
use app\store\model\Wxapi as WxapiModel;

/**
 * 客服消息推送
 * Class Article
 * @package app\api\controller
 */
class Customer extends Controller
{
	// 接收推送消息以及回复消息
	public function index(){
		// 验证请求地址
		// echo $this->checkSignature();
		// return;
		
		$params = $this->request->param();
		$txt = '客服消息接收接口:'.json_encode($params).date('Y-m-d H:i:s',time())."\n";
		// $txt = '客服消息接收Token:'.WxapiModel::getAccessToken().date('Y-m-d H:i:s',time())."\n";
    	file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
		
		//发送的用户openid
		$openid = $params['FromUserName']; // 用户的openid
		$touser = $params['ToUserName']; // 小程序的微信号

		// 接收到事件
		if($params['MsgType'] == 'event'){
		
			// 用户进入对话页面
			if($params['Event'] == 'user_enter_tempsession'){
				
				$res = db('customer')->where('type',1)->order('id desc')->find();
				if(!empty($res)){
					$this->push($openid,$res['content']);
				}
			}
		}
		// 接收到文本
		if($params['MsgType'] == 'text'){
			// 人工 or 人工客服 转发到人工那边
			if($params['Content'] == '人工' || $params['Content'] == '人工客服'){
				$arr = [];
				$arr['MsgType'] = 'transfer_customer_service';
				$arr['ToUserName'] = $openid;
				$arr['FromUserName'] = $touser;
				$arr['CreateTime'] = $params['CreateTime'];
				echo json_encode($arr);
			}else{
			
				// 关键字匹配
				$res = db('customer')->where('keywords',$params['Content'])->where('type=0')->order('id desc')->find();
				if(!empty($res)){
					$this->push_text($openid,$res['content']);
				}else{
					// 关键字没有内容时推送
					$res = db('customer')->where('type=2')->order('id desc')->find();
					// 如果无关键字推送的内容不为空时推送
					if(!empty($res)){
						$this->push_text($openid,$res['content']);
						// $data = [];
						// $data['title'] = '您对本次服务是否满意呢?';
						// $data['tail'] = '欢迎再次光临';
						// $data['list'] = [
						// 	['id'=>'101','content'=>'满意'],
						// 	['id'=>'102','content'=>'不满意']
						// 	// ['id'=>'103','content'=>'内容3'],
						// 	// ['id'=>'104','content'=>'内容4']
						// ];
						// $res = $this->push_menu($openid,$data);
						// $txt = '客服消息接收接口:'.json_encode($res).date('Y-m-d H:i:s',time())."\n";
						// file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
					}
				}
			}
		}
	}
	
	// 配置url验证
	private function checkSignature()
	{
		$params = $this->request->param();
	    $signature = $params["signature"];
	    $timestamp = $params["timestamp"];
	    $nonce = $params["nonce"];
		
	    $token = 'customermessage';
	    $tmpArr = array($token, $timestamp, $nonce);
	    sort($tmpArr, SORT_STRING);
	    $tmpStr = implode( $tmpArr );
	    $tmpStr = sha1( $tmpStr );
	
	    if ($tmpStr == $signature ) {
	        // return true;
	        return $params['echostr'];
	    } else {
	        return false;
	    }
	}
	
	
	// 文本消息推送
	private function push_text($openid,$content){
		$api = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.WxapiModel::getAccessToken();
		$arr = [];
		$arr['touser'] = $openid;
		$arr['msgtype'] = 'text';
		$arr['text'] = ['content'=>$content];
		// $txt = '客服消息接收接口:'.json_encode($arr).date('Y-m-d H:i:s',time())."\n";
    	// file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
		return WxapiModel::httpsRequest($api,json_encode($arr,JSON_UNESCAPED_UNICODE));
	}
	// 菜单消息推送
	private function push_menu($openid,$data){
		$api = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.WxapiModel::getAccessToken();
		$arr = [];
		$arr['touser'] = $openid;
		$arr['msgtype'] = 'msgmenu';
		$arr['msgmenu'] = [
			'head_content'=>$data['title'], // 菜单顶部文字
			'list'=>$data['list'], // 中间内容
			'tail_content'=>$data['tail'] // 结束内容
		];
		// $txt = '客服消息接收接口:'.WxapiModel::getAccessToken().date('Y-m-d H:i:s',time())."\n";
    	// file_put_contents($_SERVER['DOCUMENT_ROOT'].'/t.txt',$txt, FILE_APPEND);
		return WxapiModel::httpsRequest($api,json_encode($arr,JSON_UNESCAPED_UNICODE));
		// {
		//   "touser": "OPENID"
		//   "msgtype": "msgmenu",
		//   "msgmenu": {
		//     "head_content": "您对本次服务是否满意呢? "
		//     "list": [
		//       {
		//         "id": "101",
		//         "content": "满意"
		//       },
		//       {
		//         "id": "102",
		//         "content": "不满意"
		//       }
		//     ],
		//     "tail_content": "欢迎再次光临"
		//   }
		// }
		
		// {"touser":"o6EGq5UbV0ILYkHjt7hATn_Zsy74","msgtype":"msgmenu","msgmenu":{"head_content":"\u6d4b\u8bd5\u83dc\u5355\u6d88\u606f\u6807\u9898:","list":[{"id":"101","content":"\u5185\u5bb91"},{"id":"102","content":"\u5185\u5bb92"},{"id":"103","content":"\u5185\u5bb93"},{"id":"104","content":"\u5185\u5bb94"}],"tail_content":"\u6b22\u8fce\u518d\u6b21\u5149\u4e34\uff01"}}
	}
}

?>